package user

import (
	"context"

	commonSdk "github.com/wangzhe1991/grpc-sdk/pb/common"
	"github.com/wangzhe1991/grpc-sdk/pb/errorx"
	userSdk "github.com/wangzhe1991/grpc-sdk/pb/user"

	"gitee.com/krio/grpc-go-server/handler/export"
	"gitee.com/krio/grpc-go-server/internal/service/region"
	"gitee.com/krio/grpc-go-server/internal/service/user"
	"gitee.com/krio/helper/logger"
)

type UserHandler struct {
	userSdk.UnimplementedUserServer
	userSvc    *user.UserService
	countrySvc *region.CountryService
}

func NewUserHandler(us *user.UserService, cs *region.CountryService) *UserHandler {
	return &UserHandler{userSvc: us, countrySvc: cs}
}

func (u *UserHandler) Create(ctx context.Context, req *userSdk.UserCreateReq) (*userSdk.UserCreateResp, error) {
	return u.userSvc.UserAdd(ctx, req)
}

func (u *UserHandler) List(ctx context.Context, req *userSdk.UserListReq) (*userSdk.UserListResp, error) {
	return u.userSvc.List(ctx, req)
}

func (u *UserHandler) Delete(ctx context.Context, req *commonSdk.ID) (*commonSdk.EmptyResponse, error) {
	return u.userSvc.Delete(ctx, req.Id)
}

func (u *UserHandler) Detail(ctx context.Context, req *commonSdk.ID) (*userSdk.UserDetailResp, error) {
	resp, exi, err := u.userSvc.Detail(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	if !exi {
		return &userSdk.UserDetailResp{}, errorx.NotFound
	}
	logger.WithContext(ctx).Info(resp)

	return resp, nil
}

func (u *UserHandler) Export(ctx context.Context, req *userSdk.UserListReq) (*userSdk.UserListExportResp, error) {
	res, err := u.userSvc.List(ctx, req)
	if err != nil {
		return nil, err
	}

	var (
		total  int
		title  = "用户信息导出"
		titleS = []string{
			"ID",
			"SFID",
			"区域CODE",
			"手机号",
			"姓",
			"名",
			"邮箱",
		}
	)
	total = len(res.Data)

	return export.UserExport(title, titleS, total, res.Data)
}

func (u *UserHandler) DetailBySFID(ctx context.Context, req *commonSdk.SFID) (*userSdk.UserDetailResp, error) {
	resp, exi, err := u.userSvc.DetailBySFID(ctx, req.Sfid)
	if err != nil {
		return nil, err
	}
	if !exi {
		return &userSdk.UserDetailResp{}, errorx.NotFound
	}

	return resp, nil
}
